
// Definition for a binary tree node.
function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}

/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var convertBiNode = function(root) {
  if(!root || (!root.left && !root.right)) return root;
  let nodeArr = [], queue = [root];
  while(queue.length) {
    let node = queue.shift();
    nodeArr.push(node);
    if(node.left) queue.push(node.left);
    if(node.right) queue.push(node.right);
  }
  nodeArr.sort((a, b) => a.val - b.val);
  for(let i = 0; i < nodeArr.length; i++) {
    if(i == nodeArr.length - 1) {
      nodeArr[i].left = null;
      nodeArr[i].right = null;
    } else {
      nodeArr[i].left = null;
      nodeArr[i].right = nodeArr[i + 1];
    }
  }
  return nodeArr[0];
};
let root = [4,2,5,1,3,null,6,0];
console.log(convertBiNode(root));
